package common.tool.box.web.controller.utils.charset;

import common.tool.box.common.annotation.Log;
import common.tool.box.common.config.CommonToolBoxConfig;
import common.tool.box.common.constant.Constants;
import common.tool.box.common.core.domain.AjaxResult;
import common.tool.box.common.enums.BusinessType;
import common.tool.box.common.utils.file.FileUploadUtils;
import common.tool.box.common.utils.file.FileUtils;
import common.tool.box.framework.config.ServerConfig;
import common.tool.box.utils.charset.CharsetUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/utils/charset")
@Api(tags = "charset")
public class CharsetController
{
    private static final Logger log = LoggerFactory.getLogger(CharsetController.class);

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    /**
     * 文件上传并转换字符集为UTF-8
     */
    @ApiOperation("文件上传并转换字符集为UTF-8")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件", dataType = "MultipartFile", dataTypeClass = MultipartFile.class)
    })
    @PostMapping("/transcoding")
    @Log(title = "文件上传并转换字符集为UTF-8", businessType = BusinessType.TOOL)
    public AjaxResult charsetTranscoding(MultipartFile file) throws Exception
    {
        try
        {
            AjaxResult ajax = AjaxResult.success();
            // 先上传文件
            String filePath = CommonToolBoxConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String absPath = FileUploadUtils.getAbsoluteFile(filePath, fileName.split("upload")[1]).getAbsolutePath();
            CharsetUtils.fileCharsetConvert(absPath, CharsetUtils.getFileEncode(absPath), Constants.UTF8);
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
